package com.leetcode.partition6;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author `RKC`
 * @date 2022/3/2 21:44
 */
public class LC564寻找最近的回文数 {

    private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private static final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        String s = reader.readLine();
        writer.write(nearestPalindromic(s));
        writer.flush();
    }

    public static String nearestPalindromic(String s) {
        long num = Long.parseLong(s), ans = -1;
        for (Long item : get(s)) {
            if (item == num) continue;
            if (ans == -1 || abs(item - num) < abs(ans - num) || (abs(item - num) == abs(ans - num) && item < ans)) {
                ans = item;
            }
        }
        return Long.toString(ans);
    }

    private static List<Long> get(String s) {
        int n = s.length();
        List<Long> res = new ArrayList<Long>(){{
            add((long) Math.pow(10, n - 1) - 1);
            add((long) Math.pow(10, n) + 1);
        }};
        //截取前面一半前缀
        long prev = Long.parseLong(s.substring(0, (n + 1) / 2));
        for (long i = prev - 1; i <= prev + 1; i++) {
            String s1 = String.valueOf(i), s2 = reverse(s1.toCharArray());
            res.add(Long.parseLong(s1 + s2.substring(n & 1)));
        }
        return res;
    }

    private static long abs(long a) {
        return Math.abs(a);
    }

    private static String reverse(char[] a) {
        int l = 0, r = a.length - 1;
        while (l < r) {
            char t = a[l];
            a[l] = a[r];
            a[r] = t;
            l++;
            r--;
        }
        return String.valueOf(a);
    }
}
